const defaultAvatarUrl =
  'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0';

Page({
  data: {
    show: false,
    userInfo: {
      avatarUrl: defaultAvatarUrl,
      nickName: '登录/注册',
    },
    tempUserInfo: {
      avatarUrl: defaultAvatarUrl,
      nickName: '',
    },
    hasUserInfo: false,
    canIUseNicknameComp: wx.canIUse('input.type.nickname'),
    defaultUrl:
      'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0',
  },

  onLoad(options) {
    this.loadUserInfo();
  },

  loadUserInfo() {
    const userdata = wx.getStorageSync('userData');
    this.setData({ userInfo: userdata });
  },

  openDialog() {
    this.setData({ show: true });
  },

  onClose() {
    this.setData({ show: false });
  },

  async confirmUserInfo() {
    await wx.request({
      url: 'http://1.94.51.11:8850/user/login',
      method: 'POST',
      data: {
        nickName: this.data.tempUserInfo.nickName,
      },
      success: res => {
        if (res.statusCode === 200) {
          this.setData({
            userInfo: this.data.tempUserInfo,
          });
          wx.setStorageSync('session', res.header['Set-Cookie']);
          wx.setStorageSync('userData', this.data.userInfo);
        } else {
          console.log(`Request failed with status code: ${res.statusCode}`);
        }
      },
      fail: error => {
        console.log(error);
      },
    });
  },

  onChooseAvatar(e) {
    const { avatarUrl } = e.detail;
    const { nickName } = this.data.tempUserInfo;
    this.setData({
      'tempUserInfo.avatarUrl': avatarUrl,
      hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
    });
  },

  onInputChange(e) {
    const nickName = e.detail.value;
    const { avatarUrl } = this.data.tempUserInfo;
    this.setData({
      'tempUserInfo.nickName': nickName,
      hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
    });
  },
});
